package createThread.cn.tedu.threaddemo.test11;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;

class MyThreadPool{

    private BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(20);

    /**
     * 参数 n 表示线程池的线程数目
     * 1.参数做了一定的简化，忽略了线程工厂，核心线程和非核心线程，拒绝策略等到
     */
    public MyThreadPool(int n){
        for (int i = 0; i < n; i++) {
            Thread t = new Thread(()->{
               while(true){
                   try {
                       Runnable task = workQueue.take();
                       task.run();
                   } catch (InterruptedException e) {
                       throw new RuntimeException(e);
                   }
               }
            });
            /**
             * 其他前台线程结束，线程池也随着结束
             * 将线程池设置为守护线程，因为默认线程状态是非守护线程
             */
            t.setDaemon(true);
            t.start();
        }
    }

    /**
     * 向线程池中加入任务 submit
     */
    public void submit(Runnable task) throws InterruptedException {
        workQueue.put(task);
    }
}

public class Demo {
    public static void main(String[] args) throws InterruptedException {
//        ThreadPoolExecutor pool = new ThreadPoolExecutor();
        MyThreadPool myThreadPool = new MyThreadPool(20);
        for (int i = 0; i < 100000; i++) {
            int idx = i;
            myThreadPool.submit(()->{
                System.out.println(Thread.currentThread().getName()+"  "+ idx);
            });
        }
        Thread.sleep(1000);

    }
}
